[% setvar title TITLE %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Allow multiple loop variables in foreach statements</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Peter Scott &lt;<a href='mailto:peter@psdt.com'>peter@psdt.com</a>&gt;
  Date: 29 Aug 2000
  Last Modified: 6 Sep 2000
  Mailing List: <a href='mailto:perl6-language@perl.org'>perl6-language@perl.org</a>
  Number: 173
  Version: 2
  Status: Frozen</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p>Allow for a list of loop variables in for(each) statements, i.e. &amp; e.g.,</p>
<pre>      foreach my ($x, $y, $z) (@list) { ... }</pre>
<a name='DESCRIPTION'></a><h1>DESCRIPTION</h1>
<p>This has been raised by several people in the past, most recently on the
perl6-* lists by Graham Barr, who does not have time to RFC it
currently.  The semantics are (hopefully) obvious: where</p>
<pre>      foreach $var (@list)</pre>
<p>iterates through <code>@list</code>, assigning <code>$var</code> to each element in turn,</p>
<pre>      foreach ($var_1, ... $var_n) (@list)</pre>
<p>iterates through <code>@list</code> n elements at a time, assigning <code>$var_1</code> through
<code>$var_n</code> to them respectively.  If the number of elements in <code>@list</code> is
not evenly divisible by n, the remaining loop variables on the last
iteration become <code>undef</code>.</p>
<p>The most obvious usefulness is traversing a hash which has been passed in
an argument list:</p>
<pre>      sub foo {
          foreach my($key, $value) (@_) { ... }
      }
      foo(%hash);</pre>
<p>instead of having to make a temporary copy:</p>
<pre>      sub foo {
          my %h = @_;
          while (my ($key, $value) = each %h) { ... }
      }</pre>
<p>This extension does not apply to the <code>foreach</code> statement <i>modifier</i>,
since that doesn't accept a loop variable anyway.</p>
<a name='Alternatives'></a><h2>Alternatives</h2>
<p>While <code>splice</code> is frequently adduced as an alternative, this requires an
array instead of just a list, and is destructive to boot.</p>
<a name='IMPLEMENTATION'></a><h1>IMPLEMENTATION</h1>
<p>The potential parsing difficulty I came up with was how to tell that</p>
<pre>      foreach ($a,$b,$c) (@list) ...</pre>
<p>was not</p>
<pre>      foreach $_ ($a, $b, $c) (@list) ...</pre>
<p>Graham tells me that the required parentheses and block braces make it
possible for the parser to be able to tell the difference.  John Porter
suggests an alternative syntax</p>
<pre>     foreach [$a, $b, $c] (@list)</pre>
<p>which could be employed instead if there is a parsing problem.</p>
<a name='REFERENCES'></a><h1>REFERENCES</h1>
<p><i><a href='http://search.cpan.org/perldoc?perlsyn#Foreach Loops'>&quot;Foreach Loops&quot; in perlsyn</a></i></p>
</div>
